<template>
  <el-card class="table-card">
    <!-- 表格顶部工具栏 -->
    <div class="table-header">
      <div class="left">
        <h2 class="title">{{ title }}</h2>
        <!-- 批量操作区 -->
        <transition name="fade">
          <div v-if="selectedRows.length" class="batch-operations">
            <span class="count">已选 {{ selectedRows.length }} 项</span>
            <slot name="batchActions" :rows="selectedRows" :clear="clearSelection" />
          </div>
        </transition>
      </div>
      <div class="right">
        <slot name="tableActions" />
      </div>
    </div>

    <!-- 表格内容区域（可滚动） -->
    <div class="table-body">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="data"
        style="width: 100%"
        v-bind="tableProps"
        @selection-change="handleSelectionChange"
      >
        <!-- 表格列配置 -->
        <template v-for="column in processedColumns" :key="column.prop || column.type">
          <el-table-column v-bind="column">
            <template v-if="column.render" #default="scope">
              <!-- 如果返回值是VNode（组件），使用component渲染 -->
              <template v-if="typeof column.render(scope.row, scope) === 'object'">
                <component :is="column.render(scope.row, scope)" />
              </template>
              <!-- 如果返回值是字符串，直接显示 -->
              <template v-else>
                {{ column.render(scope.row, scope) }}
              </template>
            </template>
          </el-table-column>
        </template>
        <!-- 操作列 -->
        <el-table-column v-if="$slots.actions" label="操作" :width="actionsWidth" fixed="right" align="center">
          <template #default="scope">
            <div class="table-action-buttons">
              <slot name="actions" v-bind="scope" />
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页器（固定在底部） -->
    <div v-if="showPagination" class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="paginationConfig.pageSizes"
        :total="paginationConfig.total"
        :layout="isMobile ? 'prev, pager, next' : 'total, sizes, prev, pager, next, jumper'"
        :pager-count="isMobile ? 5 : 7"
        :size="isMobile ? 'small' : 'default'"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { getColumnProps, getMobilePaginationConfig } from '@/utils/tableUtils'
import { isMobileDevice } from '@/utils/domUtils'

/**
 * Props 定义
 */
const props = defineProps({
  // 页面标题
  title: {
    type: String,
    required: true,
  },
  // 表格数据
  data: {
    type: Array,
    required: true,
  },
  // 表格列配置
  columns: {
    type: Array,
    required: true,
  },
  // 表格属性
  tableProps: {
    type: Object,
    default: () => ({
      border: true,
      'table-layout': 'fixed',
      'max-height': 400,
    }),
  },
  // 是否显示分页
  showPagination: {
    type: Boolean,
    default: true,
  },
  // 分页配置
  paginationConfig: {
    type: Object,
    default: () => ({
      pageSizes: [10, 20, 30, 50],
      total: 0,
    }),
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false,
  },
  // 操作列宽度
  actionsWidth: {
    type: [Number, String],
    default: 150
  },
})

/**
 * Emits 定义
 */
const emit = defineEmits(['selection-change', 'size-change', 'current-change'])

/**
 * Refs
 */
const tableRef = ref(null)
const selectedRows = ref([])
const isMobile = ref(false)

/**
 * 分页数据
 */
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  ...props.paginationConfig,
})

/**
 * 移动端检测
 */
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

/**
 * 生命周期钩子
 */
onMounted(() => {
  checkMobile()
  window.addEventListener('resize', checkMobile)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile)
})

/**
 * 方法定义
 */
// 选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
  emit('selection-change', rows)
}

// 清空选择
const clearSelection = () => {
  tableRef.value?.clearSelection()
}

/**
 * 暴露方法和属性
 */
defineExpose({
  clearSelection,
  pagination,
  tableRef,
})

// 处理列配置
const processedColumns = computed(() => props.columns.map((column) => getColumnProps(column)))

// 分页配置
const paginationConfig = computed(() =>
  isMobileDevice() ? getMobilePaginationConfig() : props.paginationConfig,
)

// 处理分页变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  emit('size-change', size)
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  emit('current-change', page)
}
</script>

<style lang="scss" scoped>
.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0; // 关键：允许容器收缩

  :deep(.el-card__body) {
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: $font-size-base;
  }

  // 表格头部样式
  .table-header {
    padding: 8px 0;
    margin-bottom: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left {
      display: flex;
      align-items: center;
    }

    .right {
      display: flex;
      align-items: center;
    }

    .title {
      font-size: $font-size-base;
      font-weight: bold;
      margin-right: 16px;
    }

    .batch-operations {
      display: flex;
      align-items: center;

      .count {
        margin-right: 8px;
      }
    }
  }

  // 表格内容区域（新增）
  .table-body {
    flex: 1;
    overflow: auto;
    min-height: 0; // 关键：允许内容区域收缩
    margin-bottom: 0; // 移除底部间距
    position: relative; // 为了处理loading状态

    // 自定义滚动条样式
    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }

    &::-webkit-scrollbar-thumb {
      border-radius: 3px;
      background-color: var(--el-border-color-darker);
      
      &:hover {
        background-color: var(--el-text-color-secondary);
      }
    }

    &::-webkit-scrollbar-track {
      border-radius: 3px;
      background-color: var(--el-fill-color-lighter);
    }

    // Firefox 滚动条样式
    scrollbar-width: thin;
    scrollbar-color: var(--el-border-color-darker) var(--el-fill-color-lighter);

    // 表格内部滚动条样式
    :deep(.el-table__body-wrapper) {
      &::-webkit-scrollbar {
        width: 6px;
        height: 6px;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 3px;
        background-color: var(--el-border-color-darker);
        
        &:hover {
          background-color: var(--el-text-color-secondary);
        }
      }

      &::-webkit-scrollbar-track {
        border-radius: 3px;
        background-color: var(--el-fill-color-lighter);
      }

      // Firefox 滚动条样式
      scrollbar-width: thin;
      scrollbar-color: var(--el-border-color-darker) var(--el-fill-color-lighter);
    }
  }

  // 分页样式
  .pagination-container {
    padding: $font-size-base 0 0;
    margin-top: auto; // 关键：将分页推到底部
    background-color: var(--el-bg-color);
    border-top: 1px solid var(--el-border-color-lighter);
    position: sticky; // 固定在底部
    bottom: 0;
    z-index: 1;
    
    :deep(.el-pagination) {
      display: flex;
      justify-content: flex-end;
      padding: 0;
    }
  }
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .table-card {
    :deep(.el-card__body) {
      padding: $font-size-base;
    }
  }
}
</style>
